package com.example.wenqujingdian.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.ConsoleMessage;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wenqujingdian.CustomerWebView;
import com.example.wenqujingdian.R;
import com.example.wenqujingdian.conast.AudioKey;
import com.example.wenqujingdian.utils.ToastUtil;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Set;


public class WebViewTopBarActivity extends AppCompatActivity {

    private CustomerWebView progressWebview;
    private Toolbar mToolbar;
    private TextView toolbar_tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_web3_view);

        initView();
        findViewById(R.id.toolbar).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void initView() {
        String url = getIntent().getStringExtra("url");
        String title = getIntent().getStringExtra("title");
        mToolbar = findViewById(R.id.toolbar);
        toolbar_tv = findViewById(R.id.title);
        progressWebview = findViewById(R.id.web_view);
        progressWebview.loadUrl(url);
        setUpToolbar(title);
        progressWebview.addJavascriptInterface(this, "webView");
        progressWebview.setInitialScale(90);   //100代表不缩放
        progressWebview.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                Log.e("webview日志", consoleMessage.message());
                return super.onConsoleMessage(consoleMessage);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                //使弹窗变toast
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
                result.confirm();
                return true;
            }

        });
        progressWebview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url == null) return false;

                try {
                    if (!url.startsWith("http://") //
                            && !url.startsWith("https://")
                    ) {
                        //不是规范开头直接returnfalse
                        return false;
                    }
                } catch (Exception e) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    Log.i("加载资源", "异常");
                    return true;//没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
                }
                Log.i("加载资源", url);
                view.loadUrl(url);
                return true;
            }


            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
               /* if (!zhuRu(view, url)) {
                    //ToastUtil.showToast("网站url为: " + url);
                } else {
                    ToastUtil.show("语音功能已启用");
                }*/
            }
        });

    }

    private void setUpToolbar(String title) {
        mToolbar.setTitle("");
        toolbar_tv.setText(title);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             /*   if (progressWebview.canGoBack()) {
                    progressWebview.goBack();//返回上一页面
                } else {
                    finish();
                }*/
                progressWebview.destroy();
                finish();
            }
        });

    }

    //区分注入方式
    public boolean zhuRu(WebView webView, String url) {
        HashMap<String, String> urlMap = new HashMap<>();
        //期刊
        urlMap.put("/", "baozhi");
        Set<String> keys = urlMap.keySet();
        for (String key : keys) {
            if (url.contains(key)) {
                //执行特殊注入
                loadLocalJS(webView, "jquery.min");
                loadLocalJS(webView, "baseDuBao");
                loadLocalJS(webView, urlMap.get(key));
                return true;
            }
        }
        return false;

    }

    public String getFromAssets(String fileName) {
        try {
            InputStreamReader inputReader = new InputStreamReader(getResources().getAssets().open("duBaoScript/" + fileName));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            String Result = "";
            while ((line = bufReader.readLine()) != null) {
                if (!line.trim().startsWith("//")) {
                    Result += line + "\n";
                }
            }
            return Result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //注入本地js
    public void loadLocalJS(WebView webView, String jsFileName) {
        String js = getFromAssets(jsFileName + ".js");
        if (null == js) {
            ToastUtil.show("读取出错");
        }
        Log.e("注入js", js.replace("\n", ""));
        webView.loadUrl("javascript:" + js);
    }


    /**
     * 方法描述：改写物理按键——返回的逻辑
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (progressWebview.canGoBack()) {
                progressWebview.goBack();//返回上一页面
                return true;
            } else {
                this.finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @JavascriptInterface
    public String getKey() {
        return AudioKey.key;
    }
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        if (progressWebview != null) {
            Log.i("webview", "webview已经销毁");
            progressWebview.destroy();
            progressWebview = null;//释放资源
        }
        super.onDestroy();
    }
}
